/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.appconfig.core.appconfig;

import com.inspur.edp.web.appconfig.api.entity.GspAppConfig;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.StringUtility;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/03/15
 */
public class AppConfigFileManager {

    /**
     * 创建app.config.json 空结构文件
     *
     * @param appConfigFileFolderPath app.config.json文件路径
     * @return
     */
    public static GspAppConfig createEmptyAppConfigFile(String appConfigFileFolderPath) {
        GspAppConfig emptyAppConfig = GspAppConfig.getNewInstance();
        String appConfigFilePath = AppConfigFilePathGenerator.generateAppConfigFilePath(appConfigFileFolderPath);
        saveAppConfig(appConfigFilePath, emptyAppConfig);
        return emptyAppConfig;
    }

    /**
     * 读取配置文件内容
     *
     * @param appConfigFilePath 文件路径 将路径调整成为路径无关参数
     * @return
     */
    public static GspAppConfig getAppConfigWithPath(String appConfigFilePath) {
        if (StringUtility.isNullOrEmpty(appConfigFilePath)) {
            return null;
        }
        appConfigFilePath = FileUtility.getPlatformIndependentPath(appConfigFilePath);
        if (!FileUtility.exists(appConfigFilePath)) {
            return null;
        }
        String fileStr = FileUtility.readAsString(appConfigFilePath);

        // 将获取的文件内容反序列化成JSON对象
        return SerializeUtility.getInstance().deserialize(fileStr, GspAppConfig.class);
    }

    /**
     * 依据app.config.json 文件路径及具体内容保存
     *
     * @param appConfigFilePath app.config.json 文件路径
     * @param appConfig
     */
    public static void saveAppConfig(String appConfigFilePath, GspAppConfig appConfig) {
        FileUtility.writeFile(appConfigFilePath, appConfig.toJson());
    }


}
